package cn.com.homeyoda.aimate.aihealth.ui.kepu;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.lifecycle.ViewModelProviders;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.chad.library.adapter.base.BaseQuickAdapter;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

import cn.com.homeyoda.aimate.aihealth.BR;
import cn.com.homeyoda.aimate.aihealth.R;
import cn.com.homeyoda.aimate.aihealth.app.AppViewModelFactory;
import cn.com.homeyoda.aimate.aihealth.base.BaseActivity;
import cn.com.homeyoda.aimate.aihealth.bean.KePuBannerList;
import cn.com.homeyoda.aimate.aihealth.bean.MessageListBean;
import cn.com.homeyoda.aimate.aihealth.bean.MessageTitleBean;
import cn.com.homeyoda.aimate.aihealth.bean.MessageTypeListBean;
import cn.com.homeyoda.aimate.aihealth.bean.MultipleItem;
import cn.com.homeyoda.aimate.aihealth.bean.PopularListBean;
import cn.com.homeyoda.aimate.aihealth.databinding.ActivityKePuBinding;
import cn.com.homeyoda.aimate.aihealth.ui.detail.DetailActivity;
import cn.com.homeyoda.aimate.aihealth.ui.message.MessageTitleAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.message.MessageTypeAdapter;
import cn.com.homeyoda.aimate.aihealth.ui.videoinspect.DetectionResultActivity;
import cn.com.homeyoda.aimate.aihealth.utils.ShowLoadingUtil;

import static com.wzq.mvvmsmart.utils.Utils.getContext;

public class KePuActivity extends BaseActivity<ActivityKePuBinding, KePuViewModel> implements View.OnClickListener {

    private KePuAdapter kePuAdapter;

    private MessageTypeAdapter messageTypeAdapter;
    private MessageTypeListBean messageTypeListBean = new MessageTypeListBean();

    private KePuListAdapter kePuListAdapter;
    private List<PopularListBean.RowsBean> rowsBeanList = new ArrayList<>();
    private List<PopularListBean.RowsBean> searchList = new ArrayList<>();
    @Override
    public KePuViewModel initViewModel() {
        AppViewModelFactory factory = AppViewModelFactory.getInstance(getApplication());
        return ViewModelProviders.of(this, factory).get(KePuViewModel.class);
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_ke_pu;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void initData() {
        super.initData();
        // 隐藏软键盘
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        binding.titleBar.ivBack.setOnClickListener(this);
        binding.titleBar.tvTitle.setText(getString(R.string.daily_kepu));
        viewModel.titleData();
        viewModel.getKePuData("","","");
        viewModel.getBanner();
        viewModel.getPopularLisData("","","");
        initRecyclerView();
    }



    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initRecyclerView() {

        messageTypeAdapter = new MessageTypeAdapter(R.layout.message_title_item, messageTypeListBean.getData(), getApplicationContext());
        binding.setLayoutManager(new LinearLayoutManager(getApplicationContext(), LinearLayoutManager.HORIZONTAL, false));
        binding.setAdapter(messageTypeAdapter);

        messageTypeAdapter.setOnItemClickListener((adapter, view, position) -> {
            messageTypeAdapter.setPos(position);
            if(position==0){
                binding.all.setVisibility(View.VISIBLE);
                binding.other.setVisibility(View.GONE);
                Log.i("huage","binding.all=111=="+binding.all.getVisibility());
                Log.i("huage","binding.other=111=="+binding.other.getVisibility());
            }else{
                binding.all.setVisibility(View.GONE);
                binding.other.setVisibility(View.VISIBLE);
                viewModel.getPopularLisData(messageTypeAdapter.getData().get(position).getTypeName(),"","");
                Log.i("huage","binding.all=222=="+binding.all.getVisibility());
                Log.i("huage","binding.other=222=="+binding.other.getVisibility());
            }

            //viewModel.getKePuDataByType(position);
        });

        kePuAdapter = new KePuAdapter(this);
        binding.setLayoutManager1(getGridLayoutManager());
        binding.setAdapter1(kePuAdapter);
        kePuAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i("huage","position=111=="+position);
                if(kePuAdapter.getData().get(position).getItemType()==MultipleItem.KP_NORMAL){
                    PopularListBean.RowsBean kePu = (PopularListBean.RowsBean) kePuAdapter.getData().get(position).getData();
                    Intent intent = new Intent(getContext(), DetailActivity.class);
                    intent.putExtra("id", kePu.getId());
                    startActivity(intent);
                }

            }
        });

        kePuListAdapter =  new KePuListAdapter(R.layout.kepu_normal_item, rowsBeanList, getApplicationContext());
        binding.setLayoutManager2(new GridLayoutManager(this,4));
        binding.setAdapter2(kePuListAdapter);
        kePuListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Log.i("huage","position=111=="+position);
                    Intent intent = new Intent(getContext(), DetailActivity.class);
                    intent.putExtra("id", kePuListAdapter.getData().get(position).getId());
                    startActivity(intent);

            }
        });


        binding.etSearch.setOnEditorActionListener((v, actionId, event) -> {
            if (actionId == EditorInfo.IME_ACTION_SEARCH  ||
                    (event != null && event.getAction() == KeyEvent.ACTION_DOWN &&
                            event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(binding.etSearch.getWindowToken(), 0);
                String input = binding.etSearch.getText().toString();
                if(input.equals("")){
                    Toast.makeText(getContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                }else{

                    List<PopularListBean.RowsBean> result = searchList.stream()
                            .filter(p -> p.getTitle().contains(input))
                            .collect(Collectors.toList());
                    if(result.size()>0){
                        binding.all.setVisibility(View.GONE);
                        binding.other.setVisibility(View.VISIBLE);
                        viewModel.getPopularLisData(result.get(0).getType(),"","");
                    }else{
                        Toast.makeText(this,"没有相关的文章!",Toast.LENGTH_SHORT).show();
                    }
                }

                Log.d("KePuActivity", "搜索内容：" + input);
                return true;
            }
            return false;
        });
        binding.search.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String input = binding.etSearch.getText().toString();
                if(input.equals("")){
                    Toast.makeText(getContext(),"请输入内容",Toast.LENGTH_SHORT).show();
                }else{
                    List<PopularListBean.RowsBean> result = searchList.stream()
                            .filter(p -> p.getTitle().contains(input))
                            .collect(Collectors.toList());
                    if(result.size()>0){
                        binding.all.setVisibility(View.GONE);
                        binding.other.setVisibility(View.VISIBLE);
                        viewModel.getPopularLisData(result.get(0).getType(),"","");
                    }else{
                        Toast.makeText(getContext(),"没有相关的文章!",Toast.LENGTH_SHORT).show();
                    }
                }

            }
        });


    }


    private @NonNull GridLayoutManager getGridLayoutManager() {
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 4);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                MultipleItem<Object> bean = kePuAdapter.getItem(position);
                if (bean == null) return 1;
                int type = bean.getItemType();
                if (type == MultipleItem.KP_BANNER) {
                    return 2;
                }
                return 1;
            }
        });
        return gridLayoutManager;
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void initViewObservable() {
        super.initViewObservable();
        viewModel.kePuTypeData.observe(this, messageTypeListBeans -> {
            messageTypeListBean = messageTypeListBeans;
            messageTypeAdapter.setNewData(messageTypeListBean.getData());
        });

        viewModel.kePuData.observe(this, list -> kePuAdapter.setNewData(list));

        viewModel.bannerData.observe(this, bannerList -> {
//            List<KePuBannerList.DataBean> dataBean = bannerList.getData();
//            dataBean.sort(new Comparator<KePuBannerList.DataBean>() {
//                @Override
//                public int compare(KePuBannerList.DataBean p1, KePuBannerList.DataBean p2) {
//                    return p1.getSort().compareTo(p2.getSort());
//                }
//            });
            kePuAdapter.setBannerList(bannerList.getData());

        });
        viewModel.popularListData.observe(this, popularListBean -> {

            rowsBeanList = popularListBean.getRows();
            kePuListAdapter.setNewData(rowsBeanList);
            if(searchList.size()==0){
                searchList.addAll(rowsBeanList);
            }
        });
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.iv_back) {
            finish();
        }
    }

}